pub mod protocol;
pub mod cli;
pub mod process;
use serde::{Deserialize, Serialize};
use std::{
    net::IpAddr,
    time::Instant,
};


/**
0       1       2       3       4       5       6       7.      8
+-------+-------+-------+-------+-------+-------+-------+-------+
|  Magic(0xAA)  |  Version(1)   |   Type (Heartbeat/Ack/Query)  |
+-------+-------+-------+-------+-------+-------+-------+-------+
|                      Host ID (UUID 128bit)                    |
|                                                               |
+-------+-------+-------+-------+-------+-------+-------+-------+
|Hostname Length|       Hostname (UTF-8)变长                    .......
+-------+-------+-------+-------+-------+-------+-------+-------+
|                          Timestamp                            |
+-------+-------+-------+-------+-------+-------+-------+-------+
|   ListenPort  | TransferPort  |            填充                |
+-------+-------+-------+-------+-------+-------+-------+-------+
至少32字节
- Magic: 0xAA (2字节，固定值)
- Version: 1 (2字节，当前版本)
- Type: 消息类型 (4字节，Heartbeat, Ack, Query)
- Host ID: 128位UUID (16字节)
- Hostname Length: 主机名长度 (2字节)
- Hostname: 主机名 (变长UTF-8字符串)
- Timestamp: 时间戳 (8字节, Unix时间戳)
- ListenPort: 监听端口(2字节，u16)
- TransferPort: 业务端口(2字节，u16)
 */

pub struct DiscoveryFrame {
    pub magic: u8,
    pub version: u8,
    pub msg_type: MessageType,
    pub host_id: [u8; 16],
    pub hostname: String,
    pub timestamp: u64,
    pub listen_port: u16,   // 新增字段
    pub transfer_port: u16, // 新增字段
}
impl DiscoveryFrame {
    // 编码为字节流
    pub fn encode(&self) -> Vec<u8> {
        let mut buf = Vec::new();
        buf.push(self.magic);
        buf.push(self.version);
        buf.push(self.msg_type.clone() as u8);
        buf.extend_from_slice(&self.host_id);
        let name_bytes = self.hostname.as_bytes();
        buf.extend_from_slice(&(name_bytes.len() as u16).to_be_bytes());
        buf.extend_from_slice(name_bytes);
        buf.extend_from_slice(&self.timestamp.to_be_bytes());
        buf.extend_from_slice(&self.listen_port.to_be_bytes()); // 新增
        buf.extend_from_slice(&self.transfer_port.to_be_bytes()); // 新增
        buf
    }

    // 解码字节流
    pub fn decode(data: &[u8]) -> Option<Self> {
        if data.len() < 32 || data[0] != 0xAA {
            return None;
        } // 长度校验
        let host_id = data[3..19].try_into().unwrap();
        let name_len = u16::from_be_bytes([data[19], data[20]]) as usize;
        let hostname = String::from_utf8_lossy(&data[21..21 + name_len]).into_owned();
        let timestamp = u64::from_be_bytes(data[21 + name_len..29 + name_len].try_into().unwrap());
        let listen_port = u16::from_be_bytes([data[29 + name_len], data[30 + name_len]]);
        let transfer_port = u16::from_be_bytes([data[31 + name_len], data[32 + name_len]]);
        Some(Self {
            magic: data[0],
            version: data[1],
            msg_type: match data[2] {
                0x01 => MessageType::Heartbeat,
                0x02 => MessageType::Ack,
                0x03 => MessageType::Query,
                _ => return None,
            },
            host_id,
            hostname,
            timestamp,
            listen_port,
            transfer_port,
        })
    }
    pub fn build_ack_frame() -> Self {
        let address = crate::CONFIG.get().unwrap().address.clone();
        Self {
            magic: 0xAA,
            version: 0x01,
            msg_type: MessageType::Ack,
            host_id: [0; 16], // 通常为零或特定ID
            hostname: String::new(),
            timestamp: 0,
            listen_port: address.listen_port,
            transfer_port: address.transfer_port,
        }
    }
    pub fn build_heartbeat_frame(host_id: [u8; 16], hostname: String, timestamp: u64) -> Self {
        let address = crate::CONFIG.get().unwrap().address.clone();
        Self {
            magic: 0xAA,
            version: 0x01,
            msg_type: MessageType::Heartbeat,
            host_id,
            hostname,
            timestamp,
            listen_port: address.listen_port,
            transfer_port: address.transfer_port,
        }
    }
}



#[derive(Debug)]
pub enum Command {
    ListDevices, // 列出所有设备
    SearchDevices(IpAddr,u16), // 局域网ip,端口
    BroadcastDevices, // 广播搜索(8888端口)设备
    RemoveDevice(u64), // 移除设备
    ClearScreen, // 清屏
    Quit, // 退出
    Help,
    SendFile(u64, String), // 设备ID, 文件路径
}
// 文件传输命令
#[derive(Debug, Serialize, Deserialize)]
pub enum TransferCommand {
    SendFile(String, u64), // 文件名, 文件大小
    RequestFile(String),   // 请求的文件名
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeviceInfo {
    pub id: String,
    pub name: String,
    pub ip: IpAddr,
    pub transfer_port: u16,
    #[serde(skip, default = "Instant::now")]
    pub last_seen: Instant,
}


#[derive(Debug, Clone)]
pub enum MessageType {
    Heartbeat = 0x01,
    Ack = 0x02,
    Query = 0x03,
}